package com.cloud.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.net.URI;
import java.net.URISyntaxException;

public class httpServerHandle extends SimpleChannelInboundHandler<HttpObject> {

    // channelRead0 当有读取事件的触发 （读取客户端数据）
    // HttpObject 客户端和服务端相互通讯的数据被封装成HttpObject
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws URISyntaxException {
        // 判断msg是不是httpRequest请求
        if (msg instanceof HttpRequest) {
            System.out.println("msg的类型是: " + msg.getClass());
            System.out.println("客户端的地址是 " + ctx.channel().remoteAddress());

            // 获取到HttpRequest 过滤指定资源请求
            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.uri());
            if (uri.getPath().equals("/favicon.ico")) {
                System.out.println(uri+" 这个资源请求不做响应~");
                return;
            }

            // 回复信息给浏览器 返回的信息必须满足[http协议]
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);

            // 构造一个http的响应，即httpResponse
            DefaultFullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

            // 将构建好的httpResponse 返回
            ctx.writeAndFlush(fullHttpResponse);
        }
    }
}
